<template>
  <div class="detail">
       <van-nav-bar
  title="商品详情"
  left-text="返回"
  left-arrow
  @click-left="onClickLeft"
/>

<van-swipe @change="onChange" v-if="detail">
  <van-swipe-item v-for="a in detail.photo" :key="a.id">
     <img :src="a.url" alt="" style="width: 100%;">
  </van-swipe-item>

  <template #indicator>
    <div class="custom-indicator">{{ current + 1 }}/5</div>
  </template>
</van-swipe>

  <div class="desc" v-if="detail">
      <div class="title">
        <van-tag plain  color="#f00">包邮</van-tag>
        {{ detail.title }}
      </div>
      <div class="price-container">
        <span class="price">￥{{ detail.price }}</span>
      </div>
    </div>

  <div class="vant-icon">
    <van-icon name="like" size="20" :color="color" @click="changeColor"/>
    <van-icon name="star" size="20" color="yellow"/>
    <van-icon name="shopping-cart" size="20" color="#ccc" @click="handleAddToCart"/>
  </div>
    <van-divider>商品图文详情</van-divider>

    <!-- 图文详情 -->
    <div class="content" v-if="detail">
      <img
        v-for="content in detail.descContentList"
        :key="content.id"
        :src="content.url"
        style="width: 100%;"
      />
    </div>
  </div>
</template>

<script>
import { getDetail } from '@/api/detail'
export default {
  name: 'Detail',
  data() {
    return {
      detail: null,
      current: 0,
      color: '',
    }
  },
  async created() {
    const { detail } = await getDetail(this.$route.params.id)
    this.detail = detail
    console.log(this.detail)
  },
  methods: {
    onClickLeft() {
      this.$router.back()
    },
    onChange(index) {
      this.current = index
    },
    changeColor() {
      this.color = 'red'
    },
    handleAddToCart() {
      // 构建当前选购的商品对象
      const currentProduct = {
        id: this.detail.id,
        image: this.detail.image,
        title: this.detail.title,
        price: this.detail.price,
      }
      console.log('currentProduct', currentProduct.price)
      // 加入购物车，更新 vuex store 中的状态数据
      this.$store.dispatch('cart/addToCartAsync', currentProduct)
      // 提示
      this.$toast({
        type: 'success',
        message: '加入成功',
      })
    },
  },
}
</script>

<style lang="less" scoped>
  .custom-indicator {
    position: absolute;
    right: 5px;
    bottom: 5px;
    padding: 2px 5px;
    font-size: 16px;
    color:white;
    background: rgba(0, 0, 0, 0.1);
  }
  .price{
    font-size: 20px;
    color: red;
    float: left;
  }
  .vant-icon{
    display: inline;
    float:right;
    van-icon{
      padding-left: 20px;
    }
  }
</style>
